﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;

namespace WXYW
{
    public partial class ReturnToFactoryRepairAndQuoate : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }   

        // 页面信息初始化
        private void BindData()
        {
            DropDownItemService dropDownItemService = new DropDownItemService();
            customerQuatationReasonDDL.Items.Clear();
            customerQuatationReasonDDL.Items.Add("请选择收费原因");
            factoryQuatationReasonDDL.Items.Clear();
            factoryQuatationReasonDDL.Items.Add("请选择收费原因");
            List<DropDownItem> reasonList = dropDownItemService.GetAllChargeReason();
            foreach (DropDownItem reason in reasonList)
            {
                customerQuatationReasonDDL.Items.Add(new ListItem(reason.Name, reason.Name));
                factoryQuatationReasonDDL.Items.Add(new ListItem(reason.Name, reason.Name));
            }

            ReturnToFactoryService service = new ReturnToFactoryService();
            ReturnToFactoryForm form = service.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));

            ProviderService providerservice = new ProviderService();
            Provider provider = providerservice.GetProviderByCode(form.ProvideCode);
            if (provider != null)
            {
                providerNameLabel.Text = provider.ProviderName;
                connectPersonLabel.Text = provider.Contact1Name;
                proviceCodeLabel.Text = provider.ProviderCode;
                addressLabel.Text = provider.Address;
                phoneNumberLabel.Text = provider.Contact1Phone;
                cellPhoneLabel.Text = provider.Contact1MobilePhone;
                rtfRunningNumberLabel.Text = form.RunningNumber;
                workStatusLabel.Text = provider.Relation;
            }
            
            rmaCodeLabel.Text = form.ApplicationProduct.ApplicationForm.ApplicationCode;
            applicantEmailLabel.Text = form.ApplicationProduct.ApplicationForm.User.UserEmail;
            applicantLabel.Text = form.ApplicationProduct.ApplicationForm.User.FullName;
            applicantPhoneLabel.Text = form.ApplicationProduct.ApplicationForm.User.UserPhone;

            productTypeLabel.Text = form.ApplicationProduct.ProductType.ProductTypeName;
            productSerialNumberLabel.Text = form.ApplicationProduct.ProductSerialNumber;
            problemDescriptionLabel.Text = form.ApplicationProduct.ProductProblemDescription;
            receiveTimeLabel.Text = form.ApplicationProduct.ApplicationForm.ReceiveDateTime.Value.ToString("yyyy-MM-dd");
            versionLabel.Text = form.ApplicationProduct.ProductVersionNumber;
            repairStatusLbl.Text = form.ApplicationProduct.ProductRepairType;

            ApplicationProduct product = form.ApplicationProduct;
            rmaLabel.Text = product.ApplicationForm.ApplicationCode;           
            serialNumberLabel.Text = product.ProductType.ProductTypeName;
            factoryProductModelNOLbl.Text = product.ProductType.ProductTypeName;
            factoryRMALbl.Text = product.ApplicationForm.ApplicationCode;            
            versionNUmberLabel.Text = product.ProductVersionNumber;
            factoryVersionNOLbl.Text = product.ProductVersionNumber;            
            blxxTxtBox.Text = product.BLXX;        
        }              

        // 点击页面右上角保存按钮处理事件
        protected void saveLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ReturnToFactoryService returnService = new ReturnToFactoryService();
                ReturnToFactoryForm returnFactoryForm = returnService.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(returnFactoryForm.ApplicationProduct.ApplicationProductID);

                if (product.QuatationForm.IsLoaded)
                {
                    product.QuatationForm.Load();
                }
                if (product.QuatationForm.Count > 0)
                {                    
                    returnFactoryForm.ApplicationProduct.IsQuotePrice = true;
                    returnFactoryForm.ApplicationProduct.QuotationDateTime = DateTime.Now;                    
                    //returnFactoryForm.ApplicationProduct.Status = "返厂-待客户报价确认";
                    returnFactoryForm.Status = "返厂-待客户报价确认";
                }
                else if (returnFactoryForm.ReturnToFactoryQuatation.Count > 0)
                {
                    returnFactoryForm.ApplicationProduct.IsQuotePrice = false;
                    returnFactoryForm.Status = "返厂-待报价确认";
                }
                else
                {
                    returnFactoryForm.ApplicationProduct.IsQuotePrice = false;
                    returnFactoryForm.Status = "返厂-待收货确认";
                }

                returnService.Update(returnFactoryForm);

                ClientScript.RegisterStartupScript(this.GetType(), "tip", "alert('保存成功！');location.href='ReturnToFactoryNeedMaintain.aspx';", true);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ReturnToFactoryRepairAndQuoate.aspx::saveLinkButton_Click");
            }
        }       
                

        #region 客户报价
        // 点击客户报价链接事件处理程序
        protected void customerQuotrPriceLnkBtn_Click(object sender, EventArgs e)
        {
            ResetCustomerQuatationForm();
            ReturnToFactoryService returnService = new ReturnToFactoryService();
            ReturnToFactoryForm returnFactoryForm = returnService.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
            BindAccessoryGridView(returnFactoryForm.ApplicationProduct.ApplicationProductID);
            quatationModalPopupExtender.Show();
        }

        // 添加客户报价条目
        protected void CustomerQuatationAddAccessoryButton_Click(object sender, EventArgs e)
        {
            string result = ValidateQuatation(CustomerQuatationAccessoryTxtBox.Text,
                CustomerQuataionAccessoryPriceTxtBox.Text,
                CustomerQuatationCountDDL.SelectedValue);
            if (string.IsNullOrEmpty(result))
            {
                ReturnToFactoryService returnService = new ReturnToFactoryService();
                ReturnToFactoryForm returnFactoryForm = returnService.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));

                QuatationForm form = new QuatationForm
                {
                    AccessoryName = CustomerQuatationAccessoryTxtBox.Text,
                    Cost = Convert.ToDouble(CustomerQuataionAccessoryPriceTxtBox.Text) * Convert.ToInt32(CustomerQuatationCountDDL.SelectedValue),
                    Reason = customerQuatationReasonDDL.SelectedValue,
                    UnitPrice = Convert.ToDecimal(CustomerQuataionAccessoryPriceTxtBox.Text),
                    Count = Convert.ToInt32(CustomerQuatationCountDDL.SelectedValue)
                };
                if (isBWBACheckBox.Checked)
                {
                    form.IsBWBA = true;
                }
                else
                {
                    form.IsBWBA = false;
                }

                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(returnFactoryForm.ApplicationProduct.ApplicationProductID);
                product.QuatationForm.Add(form);

                if (customerQuatationReasonDDL.SelectedIndex > 0)
                {
                    product.ReasonOfCost = customerQuatationReasonDDL.SelectedValue;
                }
                if (!string.IsNullOrEmpty(blxxTxtBox.Text))
                {
                    product.BLXX = blxxTxtBox.Text;
                }

                product.IsQuotePrice = true; // 2013.8.31 添加
                product.QuotationDateTime = DateTime.Now; // 2013.8.31 添加
                service.UpdateProduct(product);            
                
                ResetCustomerQuatationForm();
                BindAccessoryGridView(returnFactoryForm.ApplicationProduct.ApplicationProductID);
            }
            else
            {
                CustomerQuatationTipLbl.Text = result;
            }
        }

        // 点击客户报价对话框上的保存按钮
        protected void saveCustomerQuatationLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string result = ValidateQuatation(CustomerQuatationAccessoryTxtBox.Text,
                    CustomerQuataionAccessoryPriceTxtBox.Text,
                    CustomerQuatationCountDDL.SelectedValue);
                ReturnToFactoryService returnService = new ReturnToFactoryService();
                ReturnToFactoryForm returnFactoryForm = returnService.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(returnFactoryForm.ApplicationProduct.ApplicationProductID);
                if (string.IsNullOrEmpty(result))
                {
                    if (customerQuatationReasonDDL.SelectedIndex == 0)
                    {
                        CustomerQuatationTipLbl.Text = "请选择报价原因！";
                        quatationModalPopupExtender.Show();
                    }
                    else
                    {
                        if (!product.QuatationForm.IsLoaded)
                        {
                            product.QuatationForm.Load();
                        }

                        QuatationForm form = new QuatationForm
                        {
                            AccessoryName = CustomerQuatationAccessoryTxtBox.Text,
                            UnitPrice = Convert.ToDecimal(CustomerQuataionAccessoryPriceTxtBox.Text),
                            Cost = Convert.ToDouble(CustomerQuataionAccessoryPriceTxtBox.Text) * Convert.ToInt32(CustomerQuatationCountDDL.SelectedValue),
                            Reason = customerQuatationReasonDDL.SelectedValue,
                            Count = Convert.ToInt32(CustomerQuatationCountDDL.SelectedValue)
                        };
                        if (!string.IsNullOrEmpty(blxxTxtBox.Text))
                        {
                            product.BLXX = blxxTxtBox.Text;
                        }
                        if (isBWBACheckBox.Checked)
                        {
                            form.IsBWBA = true;
                        }

                        //if (product.QuatationForm == null)
                        //{
                        //    product.QuatationForm = new System.Data.Objects.DataClasses.EntityCollection<QuatationForm>();
                        //}
                        product.QuatationForm.Add(form);
                        product.QuotationDateTime = DateTime.Now;
                        product.IsQuotePrice = true;
                        product.ReasonOfCost = customerQuatationReasonDDL.SelectedValue;
                        if (!string.IsNullOrEmpty(blxxTxtBox.Text))
                        {
                            blxxTxtBox.Text = product.BLXX;
                        }
                        service.UpdateProduct(product);

                        BindAccessoryGridView(product.ApplicationProductID);
                    }
                }
                //else
                //{
                //    CustomerQuatationTipLbl.Text = "您未添加任何报价零件！";
                //    quatationModalPopupExtender.Show();
                //}
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ReturnToFactoryRepairAndQuoate.aspx::saveCustomerQuatationLnkBtn_Click");
                throw ex;
            }
        }
        // 删除客户报价条目
        protected void deleteLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ReturnToFactoryService returnService = new ReturnToFactoryService();
                ReturnToFactoryForm returnFactoryForm = returnService.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));

                long quatationFormID = long.Parse(((LinkButton)sender).CommandArgument);
                ApplicationProductService service = new ApplicationProductService();
                service.DeleteQuatationFormByID(quatationFormID);

                if (!returnFactoryForm.ApplicationProductReference.IsLoaded)
                {
                    returnFactoryForm.ApplicationProductReference.Load();
                }
                ApplicationProduct applicationProduct = service.GetApplicationProductByID(returnFactoryForm.ApplicationProduct.ApplicationProductID);
                if (!applicationProduct.QuatationForm.IsLoaded)
                {
                    applicationProduct.QuatationForm.Load();
                }
                if (applicationProduct.QuatationForm.Count == 0)
                {
                    applicationProduct.QuotationDateTime = null;
                    applicationProduct.ReasonOfCost = "";
                    applicationProduct.IsQuotePrice = false;
                    service.UpdateProduct(applicationProduct);
                }
                
                BindAccessoryGridView(returnFactoryForm.ApplicationProduct.ApplicationProductID);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ReturnToFactoryRepairAndQuoate.aspx::deleteLinkButton_Click");
            }
        }     

        private void BindAccessoryGridView(long productID)
        {
            ApplicationProductService service = new ApplicationProductService();
            CustomerQuatationGridView.DataSource = service.GetQuatationFormByProductID(productID);
            CustomerQuatationGridView.DataBind();

            ReturnToFactoryService returnService = new ReturnToFactoryService();
            ReturnToFactoryForm returnFactoryForm = returnService.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
            ApplicationProduct product = service.GetApplicationProductByID(returnFactoryForm.ApplicationProduct.ApplicationProductID);
            if (!product.QuatationForm.IsLoaded)
            {
                product.QuatationForm.Load();
            }
            if (product.QuatationForm != null && product.QuatationForm.Count > 0)
            {
                customerQuatationReasonDDL.SelectedValue = product.ReasonOfCost;
            }
            else
            {
                customerQuatationReasonDDL.SelectedIndex = 0;
            }
        }

        protected void CustomerQuatationGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }        

        protected void CustomerQuatationAccessoryTxtBox_TextChanged(object sender, EventArgs e)
        {
            ProviderService providerService = new ProviderService();
            ProviderAccessory accessory = providerService.GetAccessoryByName(CustomerQuatationAccessoryTxtBox.Text);
            if (accessory != null)
            {
                CustomerQuataionAccessoryPriceTxtBox.Text = Math.Round(accessory.CustomerPrice.Value, 2).ToString();
            }
        }

        private void ResetCustomerQuatationForm()
        {
            CustomerQuatationAccessoryTxtBox.Text = "";
            CustomerQuataionAccessoryPriceTxtBox.Text = "";
            isBWBACheckBox.Checked = false;
            customerQuatationReasonDDL.SelectedIndex = 0;
            CustomerQuatationCountDDL.SelectedIndex = 0;
            CustomerQuatationTipLbl.Text = "";
        }

        private string ValidateQuatation(string p, string p_2, string p_3)
        {
            string result = string.Empty;
            if (string.IsNullOrEmpty(p))
            {
                result += "没有输入零件\n";
            }
            if (string.IsNullOrEmpty(p_2))
            {
                result += "没有价格\n";
            }
            if (p_3.Equals("0"))
            {
                result += "请选择收费原因";
            }

            return result;
        }
        #endregion

        #region 工厂报价

        protected void factoryQuotePriceLinkButton_Click(object sender, EventArgs e)
        {
            ResetFactoryQuatationForm();
            BindQuatationList();
            factoryQuatationModalPopupExtender.Show();
        }
        // 点击工厂报价对话框上的保存按钮
        protected void saveFactoryQuatationBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (factoryQuatationReasonDDL.SelectedIndex == 0)
                {
                    factoryTipLbl.Text = "请选择报价原因！";
                    factoryQuatationModalPopupExtender.Show();
                }
                else
                {
                    string result = ValidateQuatation(factoryQuatationAccessoryTxtBox.Text,
                       factoryQuatationPriceTxtBox.Text,
                       factoryQuatationCountDDL.SelectedValue);
                    if (string.IsNullOrEmpty(result))
                    {
                        ReturnToFactoryService service = new ReturnToFactoryService();
                        ReturnToFactoryQuatation quatationItem = new ReturnToFactoryQuatation();
                        quatationItem.AccessoryName = factoryQuatationAccessoryTxtBox.Text;
                        quatationItem.Count = Convert.ToInt32(factoryQuatationCountDDL.SelectedValue);
                        quatationItem.LastUpdate = DateTime.Now;
                        quatationItem.LastUpdateBy = ContextService.CurrentAccount.UserID;
                        quatationItem.ReturnToFactoryForm = service.GetReturnToFactoryFormByID(Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
                        quatationItem.UnitPrice = Convert.ToDecimal(factoryQuatationPriceTxtBox.Text);
                        service.AddQuatation(quatationItem);

                        ReturnToFactoryForm form = service.GetReturnToFactoryFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
                        if (!form.ApplicationProductReference.IsLoaded)
                        {
                            form.ApplicationProductReference.Load();
                        }
                        form.ProviderQuatationDate = DateTime.Now;
                        form.QuatationReason = factoryQuatationReasonDDL.SelectedValue;
                        service.Update(form);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, string.Format("ReturnToFactoryRepairAndQuoate.aspx -> saveFactoryQuatationBtn_Click"));
                throw ex;
            }
        }

        // 添加工厂报价项目
        protected void factoryAddQuatationBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string result = ValidateQuatation(factoryQuatationAccessoryTxtBox.Text,
                factoryQuatationPriceTxtBox.Text,
                factoryQuatationCountDDL.SelectedValue);
                if (string.IsNullOrEmpty(result))
                {
                    ReturnToFactoryService service = new ReturnToFactoryService();
                    ReturnToFactoryQuatation quatationItem = new ReturnToFactoryQuatation();
                    quatationItem.AccessoryName = factoryQuatationAccessoryTxtBox.Text;
                    quatationItem.Count = Convert.ToInt32(factoryQuatationCountDDL.SelectedValue);
                    quatationItem.LastUpdate = DateTime.Now;
                    quatationItem.LastUpdateBy = ContextService.CurrentAccount.UserID;
                    quatationItem.ReturnToFactoryForm = service.GetReturnToFactoryFormByID(Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
                    quatationItem.UnitPrice = Convert.ToDecimal(factoryQuatationPriceTxtBox.Text);
                    service.AddQuatation(quatationItem);


                    ResetFactoryQuatationForm();
                    BindQuatationList();
                }
                else
                {
                    factoryTipLbl.Text = result;
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, string.Format("ReturnToFactoryRepairAndQuoate.aspx -> factoryAddQuatationBtn_Click"));
                throw ex;
            }
        }
        // 删除报价项目
        protected void factoryDeleteQuatationLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ReturnToFactoryService service = new ReturnToFactoryService();
                service.RemoveQuatation(Convert.ToInt64(((LinkButton)sender).CommandArgument));

                ReturnToFactoryForm returnToFactoryForm = service.GetReturnToFactoryFormByID(Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
                if (!returnToFactoryForm.ReturnToFactoryQuatation.IsLoaded)
                {
                    returnToFactoryForm.ReturnToFactoryQuatation.Load();
                }
                if (returnToFactoryForm.ReturnToFactoryQuatation.Count == 0)
                {
                    returnToFactoryForm.QuatationReason = "";
                    returnToFactoryForm.ProviderQuatationDate = null;
                    service.Update(returnToFactoryForm);
                }
                

                BindQuatationList();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, string.Format("ReturnToFactoryRepairAndQuoate.aspx -> factoryDeleteQuatationLnkBtn_Click"));
            }
        }

        private void BindQuatationList()
        {
            ReturnToFactoryService service = new ReturnToFactoryService();
            factoryQuatationGridView.DataSource = service.GetQuatationList(Convert.ToInt64(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
            factoryQuatationGridView.DataBind();

            ReturnToFactoryForm returnFactoryForm = service.GetReturnToFactoryFormProductDetail(long.Parse(Request.QueryString[Constants.QUERYSTR_RETURNTOFACTORY_ID]));
            if (!string.IsNullOrEmpty(returnFactoryForm.QuatationReason))
            {
                factoryQuatationReasonDDL.SelectedValue = returnFactoryForm.QuatationReason;
            }
        }

        private void ResetFactoryQuatationForm()
        {
            factoryQuatationAccessoryTxtBox.Text = string.Empty;
            factoryQuatationPriceTxtBox.Text = string.Empty;
            factoryQuatationCountDDL.SelectedIndex = 0;
            factoryTipLbl.Text = "";
        }

        protected void factoryQuatationAccessoryTxtBox_TextChanged(object sender, EventArgs e)
        {
            ProviderService providerService = new ProviderService();
            ProviderAccessory accessory = providerService.GetAccessoryByName(factoryQuatationAccessoryTxtBox.Text);
            if (accessory != null)            
            {
                factoryQuatationPriceTxtBox.Text = Math.Round(accessory.Price.Value, 2).ToString();
            }
        }

        protected void factoryQuatationGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            }
        }        
        #endregion
    }
}
